package day02;

import ch.qos.logback.core.joran.action.NewRuleAction;
import lombok.extern.slf4j.Slf4j;

/**
 * 保护性暂停
 */
@Slf4j
public class Test5 {

    public static void main(String[] args) {
        GuardObject guardObject = new GuardObject();
        new Thread(()->{
            try {
                log.debug("等待下载");
                Object obj = guardObject.get(2000);
                log.debug("下载结果: {}",obj);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"t1").start();


        new Thread(()->{
            log.debug("执行下载");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            guardObject.complete("下载完成");
        },"t2").start();

    }


}

/**
 * 设计模式
 */
class GuardObject{
    private Object response;

    // 获取值
    public Object get(long timeout) throws InterruptedException {
        synchronized (this){
            long passtime = 0L;
            long begin = System.currentTimeMillis();
            // 假设我设置了 2s 超时
            while(response == null){
                if(passtime >= timeout){
                    break;
                }
                // 虚假唤醒
                // 假设wait在1s时候被唤醒
                this.wait(timeout-passtime);
                // passtime就变成了1s 这时候就再次循环判断,还是会继续等待timeout的话还是会等待两秒,如果是timeout - passtime就会等待1秒 就正常了
                passtime = System.currentTimeMillis() - begin;
            }

            if(response == null){
                return "已超时";
            }
            return response;
        }
    }

    // 设置值
    public void complete(Object response) {
        synchronized (this){
            // 给结果成员变量赋值
            this.response = response;
        }
    }
}
